package com.mooc.lib_sofa.ui.sofa

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.mooc.ijk.widget.IJKView
import com.mooc.lib_common.action.BusAction
import com.mooc.lib_common.action.BusConst
import com.mooc.lib_common.arouter.service.UserLoginAService
import com.mooc.lib_common.model.FeedDissEntity
import com.mooc.lib_common.model.FeedLikeEntity
import com.mooc.lib_common.model.FeedShareEntity
import com.mooc.lib_common.mvvm.BaseFragment
import com.mooc.lib_sofa.BR
import com.mooc.lib_sofa.R
import com.mooc.lib_sofa.adapter.SofaFeedAdapter
import com.mooc.lib_sofa.adapter.SofaVpAdapter
import com.mooc.lib_sofa.databinding.FragmentSofaBinding
import com.mooc.lib_sofa.databinding.LayoutSofaListBinding
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * tablayout 值处理
 * ViewPager以及VP下的RecyclerView处理
 * 基于ViewPager自定义属性->传递数据源以及viewPager适配器
 * */
class SofaFragment : BaseFragment<SofaViewModel, FragmentSofaBinding>(),OnItemChildClickListener, UMShareListener {

    lateinit var vpAdapter : SofaVpAdapter
    lateinit var vp : ViewPager
    lateinit var views : ArrayList<View>//vp下展示的上下拉刷新列表
    var titles:ArrayList<String> = java.util.ArrayList()
    val picsAdapter = SofaFeedAdapter()
    val videoAdapter = SofaFeedAdapter()
    val textAdapter = SofaFeedAdapter()
    val scrolistener : RecyclerView.OnScrollListener = object : RecyclerView.OnScrollListener(){

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            val tag = recyclerView.tag as String
            //当前为video列表滑动停止
            if (newState == RecyclerView.SCROLL_STATE_IDLE&&tag.equals("video")){
                //获取最上一条完整显示索引
                val manager : LinearLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                val possion = manager.findFirstCompletelyVisibleItemPosition()
                //停止列表中全部播放器播放
                var index = 0
                while (index < videoAdapter.itemCount){
                    index ++
                    val view = videoAdapter.getViewByPosition(index, R.id.sofa_player_view)
                    if (null == view)
                        continue
                    val ijk :IJKView = view as IJKView
                    if (ijk.isPlay())
                        ijk.relase()
                }
                val view = videoAdapter.getViewByPosition(possion, R.id.sofa_player_view)
                if (view!=null) {
                    val ijk: IJKView = videoAdapter.getViewByPosition(possion, R.id.sofa_player_view) as IJKView
                    ijk.setPath(videoAdapter.data[possion].url!!)
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshLogin(action: BusAction){
        //登录返回->data处理掉从那个item子控件监听跳转的
        if (action.equals(BusConst.LOGINACTION)){
            val type : Int= action.data!!.get("type") as Int
            if (type == 1){
                //点赞
                vm.like(itemId, itemType!!)
            }else if (type == 2){
                //踩
                vm.diss(itemId, itemType!!)
            }else if (type == 3){
                //评论数量
            }
        }
    }

    override fun initView() {
        views = ArrayList<View>()
        vp = v.sofaVp
        createViews()
        //添加顶部tablayout数据源
        titles.add("图片")
        titles.add("视频")
        titles.add("文本")
        picsAdapter.tag = SofaViewModel.PICS
        videoAdapter.tag = SofaViewModel.VIDEO
        textAdapter.tag = SofaViewModel.TXT
        picsAdapter.setOnItemChildClickListener(this)
        videoAdapter.setOnItemChildClickListener(this)
        textAdapter.setOnItemChildClickListener(this)
        vpAdapter = SofaVpAdapter(titles, views)
        vp.adapter = vpAdapter
        v.sofaTab.setViewPager(vp)
    }

    //生成获取Viewpager数据源
    fun createViews(){
        //获取图片列表对象
        val v1 = DataBindingUtil.inflate<LayoutSofaListBinding>(
                LayoutInflater.from(context), R.layout.layout_sofa_list, null, false
        )
        //添加区分标识
        v1.sofaSmart.tag = "pics"
        v1.sofaRv.tag = "pics"
        v1.setVariable(BR.listener, vm)
        v1.setVariable(BR.scrolllistener, scrolistener)
        v1.setVariable(BR.adapter, picsAdapter)
        //获取图片列表缓冲池提供给视频列表以及文字列表进行复用
        val pool :RecyclerView.RecycledViewPool = v1.sofaRv.recycledViewPool
        views.add(v1.root)
        //获取视频列表对象
        val v2 = DataBindingUtil.inflate<LayoutSofaListBinding>(
                LayoutInflater.from(context), R.layout.layout_sofa_list, null, false
        )
        //添加区分标识
        v2.sofaSmart.tag = "video"
        v2.sofaRv.tag = "video"
        v2.sofaRv.setRecycledViewPool(pool)
        v2.setVariable(BR.listener, vm)
        v2.setVariable(BR.scrolllistener, scrolistener)
        v2.setVariable(BR.adapter, videoAdapter)
        views.add(v2.root)
        //获取文字列表对象
        val v3 = DataBindingUtil.inflate<LayoutSofaListBinding>(
                LayoutInflater.from(context), R.layout.layout_sofa_list, null, false
        )
        //添加区分标识
        v3.sofaSmart.tag = "text"
        v3.sofaRv.tag = "text"
        v3.sofaRv.setRecycledViewPool(pool)
        v3.setVariable(BR.listener, vm)
        v3.setVariable(BR.scrolllistener, scrolistener)
        v3.setVariable(BR.adapter, textAdapter)
        views.add(v3.root)
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_sofa
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun initData() {
        EventBus.getDefault().register(this)
        bindListData()
        bindUgcData()
        vm.sofaRefresh("pics")
        vm.sofaRefresh("video")
        vm.sofaRefresh("text")
    }

    fun bindUgcData(){
        vm.likeBus.observe(this, {
            refreshLike(it)
        })
        vm.dissBus.observe(this, {
            refreshDiss(it)
        })
        vm.shareBus.observe(this, {
            refreshShare(it)
        })
    }

    fun refreshLike(entity: FeedLikeEntity){
        //区分列表
        if (entity.itemType.equals(SofaViewModel.PICS)){
            var index = 0
            while (index< picsAdapter.itemCount){
                var item = picsAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasLiked = entity.data!!.hasLiked
                    if (item.ugc!!.hasLiked){
                        item.ugc!!.likeCount++
                    }else
                        item.ugc!!.likeCount--
                    picsAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.VIDEO)){
            var index = 0
            while (index < videoAdapter.itemCount){
                var item = videoAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasLiked = entity.data!!.hasLiked
                    if (item.ugc!!.hasLiked){
                        item.ugc!!.likeCount++
                    }else
                        item.ugc!!.likeCount--
                    videoAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.TXT)){
            var index = 0
            while (index < textAdapter.itemCount){
                var item = textAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasLiked = entity.data!!.hasLiked
                    if (item.ugc!!.hasLiked){
                        item.ugc!!.likeCount++
                    }else
                        item.ugc!!.likeCount--
                    textAdapter.setData(index, item)
                }
                index ++
            }
        }
    }

    fun refreshDiss(entity: FeedDissEntity){
        if (entity.itemType.equals(SofaViewModel.PICS)){
            var index = 0
            while (index< picsAdapter.itemCount){
                var item = picsAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasDissed = entity.data!!.hasLiked
                    picsAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.VIDEO)){
            var index = 0
            while (index < videoAdapter.itemCount){
                var item = videoAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasDissed = entity.data!!.hasLiked
                    videoAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.TXT)){
            var index = 0
            while (index < textAdapter.itemCount){
                var item = textAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.hasDissed = entity.data!!.hasLiked
                    textAdapter.setData(index, item)
                }
                index ++
            }
        }
    }

    fun refreshShare(entity: FeedShareEntity){
        if (entity.itemType.equals(SofaViewModel.PICS)){
            var index = 0
            while (index< picsAdapter.itemCount){

                var item = picsAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.shareCount++
                    picsAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.VIDEO)){
            var index = 0
            while (index < videoAdapter.itemCount){
                var item = videoAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.shareCount++
                    videoAdapter.setData(index, item)
                }
                index ++
            }
        }else if (entity.itemType.equals(SofaViewModel.TXT)){
            var index = 0
            while (index < textAdapter.itemCount){
                var item = textAdapter.getItem(index)
                if (item.itemId == entity.itemId){
                    item.ugc!!.shareCount++
                    textAdapter.setData(index, item)
                }
                index ++
            }
        }
    }

    fun bindListData(){
        vm.picsRefreshBus.observe(this, {
            picsAdapter.setNewInstance(it.data)
        })
        vm.videoRefreshBus.observe(this, {
            videoAdapter.setNewInstance(it.data)
        })
        vm.textRefreshBus.observe(this, {
            textAdapter.setNewInstance(it.data)
        })
        vm.picsLoadBus.observe(this, {
            if (it.data == null)
                return@observe
            if (it.data!!.size == 0)
                return@observe
            picsAdapter.addData(it.data!!)
        })
        vm.videoLoadBus.observe(this, {
            if (it.data == null)
                return@observe
            if (it.data!!.size == 0)
                return@observe
            videoAdapter.addData(it.data!!)
        })
        vm.textLoadBus.observe(this, {
            if (it.data == null)
                return@observe
            if (it.data!!.size == 0)
                return@observe
            textAdapter.addData(it.data!!)
        })
    }

    var itemId:Long = 0
    var itemType : String ?= null
    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val feedAdapter : SofaFeedAdapter = adapter as SofaFeedAdapter
        itemType = feedAdapter.tag
        itemId = feedAdapter.getItem(position).itemId
        if (view.id == R.id.like) {
            val isLogin : Boolean = (ARouter.getInstance().build("/lib_user/UserLoginService").
            navigation() as UserLoginAService).isLogin()
            if (!isLogin){
                ARouter.getInstance().build("/lib_user/LoginActivity").
                navigation()
                return
            }
            //由于当前界面处于sofafragment,登录为另外的activity:界面间通信问题
            //1.eventbus;2activity返回值方式启动;3广播
            vm.like(itemId, itemType!!)
        }else if (view.id == R.id.diss) {
            val isLogin : Boolean = (ARouter.getInstance().build("/lib_user/UserLoginService").
            navigation() as UserLoginAService).isLogin()
            if (!isLogin){
                ARouter.getInstance().build("/lib_user/LoginActivity").
                navigation()
                return
            }
            vm.diss(itemId, itemType!!)
        } else if (view.id == R.id.share){
            Log.e("ZXY", "share")
//            ShareAction(activity).withText("hello"+System.currentTimeMillis()).setPlatform(SHARE_MEDIA.SINA).share()
            //sina同一条数据3min/5min只能发一次
            //分享成功后更改分享条数
            ShareAction(activity).withText("hello" + System.currentTimeMillis())
                    .setCallback(this)
                    .setPlatform(SHARE_MEDIA.SINA)
                    .share()
            itemid = itemId
            type = itemType

        }else{
            //评论
            val isLogin : Boolean = (ARouter.getInstance().build("/lib_user/UserLoginService").
            navigation() as UserLoginAService).isLogin()
            if (!isLogin){
                ARouter.getInstance().build("/lib_user/LoginActivity").
                navigation()
                return
            }
        }
//            vm.share(itemId,itemType!!)
    }

    var itemid : Long = 0
    var type : String ?=null

    override fun onStart(p0: SHARE_MEDIA?) {
    }

    override fun onResult(p0: SHARE_MEDIA?) {
        if (p0 == SHARE_MEDIA.SINA){
            //更新分享条数
            vm.share(itemid, type!!)
        }
    }

    override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
        ToastUtils.showShort(p1!!.message)
    }

    override fun onCancel(p0: SHARE_MEDIA?) {
    }

}